package partie1;
//http://stackoverflow.com/questions/2165006/simple-java-client-server-program
//http://edn.embarcadero.com/article/31995

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author fokasu
 */
public class Client {
    
    private String hostname;
    private int port;
    Socket socketClient;

    public Client(String hostname, int port)
    {
        this.hostname = hostname;
        this.port = port;
    }
    
    public void connect() throws UnknownHostException, IOException{
        System.out.println("Attempting to connect to "+hostname+":"+port);
        socketClient = new Socket(hostname,port);
        System.out.println("Connection Established");
    }
    
    public boolean readResponse() throws IOException{
        OutputStreamWriter writer = new OutputStreamWriter(new BufferedOutputStream(socketClient.getOutputStream()));
        
        String line = "";
        while (true)
        { 
            System.out.print("client > ");
            line = new BufferedReader(new InputStreamReader(System.in)).readLine();

            writer.write(line + (char) 13);
            writer.flush();
            
            if (line.toLowerCase().equals("exit"))
                break;
        }
        
        writer.close();
        return false;
    }
    
    public static void main(String[] args) 
    {
        
        Client client = new Client ("localhost",8080);
        try 
        {
            //trying to establish connection to the server
            client.connect();
            
            //if successful, read response from server
            while(true)
                client.readResponse();
            
        } 
        catch (UnknownHostException e) 
        {
            System.out.println("Host unknown. Cannot establish connection");
        } 
        catch (IOException e) 
        {
            System.out.println("Cannot establish connection. Server may not be up. "+e.getMessage());
        }
    }
    
}
